package com.prd.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.prd.config.LoginInterceptor;
import com.prd.dto.SysDeptDTO;
import com.prd.model.SysDeptDO;
import com.prd.mapper.SysDeptMapper;
import com.prd.service.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.util.CommonUtil;
import com.prd.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 部门组织数据表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2024-01-04
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDeptDO> implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * add
     * @param sysDeptDTO
     * @return
     */
    @Override
    public JsonData add(SysDeptDTO sysDeptDTO) {

        SysDeptDO sysDeptDO = sysDeptMapper.selectOne(new LambdaQueryWrapper<SysDeptDO>().eq(SysDeptDO::getDeptName, sysDeptDTO.getDeptName()));

        if (sysDeptDO != null) {
            return JsonData.buildError("部门已存在。");
        }

        sysDeptDTO.setCreateBy(LoginInterceptor.threadLocal.get().getName());
        sysDeptDTO.setCreatedTime(LocalDateTime.now());
        sysDeptMapper.insert(CommonUtil.dtoTransfer(sysDeptDTO, SysDeptDO.class));

        return JsonData.buildSuccess();
    }

    /**
     * 编辑
     * @param sysDeptDTO
     * @return
     */
    @Override
    public JsonData editDept(SysDeptDTO sysDeptDTO) {

        sysDeptMapper.updateById(CommonUtil.dtoTransfer(sysDeptDTO, SysDeptDO.class));

        return JsonData.buildSuccess();
    }

    /**
     * 移除
     * @param id
     * @return
     */
    @Override
    public JsonData delete(Long id) {

        sysDeptMapper.deleteById(id);

        return JsonData.buildSuccess();
    }

    /**
     * 部门组织列表
     * @return
     */
    @Override
    public JsonData selectList() {

        return JsonData.buildSuccess(sysDeptMapper.selectList(new LambdaQueryWrapper<SysDeptDO>().orderBy(false,false,SysDeptDO::getCreatedTime)));
    }

    /**
     * 查询部门组织
     * @param id
     * @return
     */
    @Override
    public JsonData select(Long id) {

        return JsonData.buildSuccess(sysDeptMapper.selectById(id));
    }
}
